package com.nativetalk.service.member.register;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.*;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.member.*;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.send.TwNtSendHisInsert;
import com.nativetalk.bean.sms.Sms;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.*;
import com.nativetalk.dto.MemberLoginByCode;
import com.nativetalk.dto.MemberRegisterByCode;
import com.tls.tls_sigature.tls_sigature;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service(value = "memberRegisterService")
public class MemberRegisterServiceImpl implements MemberRegisterService {
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TwNtSendHisDao twNtSendHisDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtCooperationDao tdNtCooperationDao;
    private static Logger logger = Logger.getLogger(MemberRegisterServiceImpl.class);

    @Resource
    private RongCloudConfig rongCloudConfig;

    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/";

    @Resource
    private MembNewUserScholarshipDao membNewUserScholarshipDao;

    @Resource
    private DiscountCouponDao discountCouponDao;

    @Override
    public RetInfo register(TdNtMemberRegister member, int version) {
        String logInfo = this.getClass().getName() + ":register:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Object o_vcode = MemcachedUtils.get("register" + member.getMemb_phone());//读取缓存中的验证码
            logger.info("读取缓存中的验证码:"+o_vcode.toString());
            String userCode = member.getCode();
            logger.info("用户输入的验证码:"+userCode);
            if (o_vcode == null || !userCode.trim().equals(o_vcode.toString())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.CODE.ERROR"));
            } else {
                TdNtMemberRegisterSms memberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(member.getMemb_phone());
                /**
                 * 判断用户是否已存在
                 */
                if (memberRegisterSms != null) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MEMBER.REGISTER.ERROR"));
                } else {
                    TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
                    tdNtMemberRegister.setMemb_phone(member.getMemb_phone());
                    tdNtMemberRegister.setMemb_password(member.getMemb_password());
                    tdNtMemberRegister.setInvite_code(member.getInvite_code());
                    tdNtMemberRegister.setMemb_phone_area(member.getMemb_phone_area());
                    tdNtMemberRegister.setEqu_client_id(member.getEqu_client_id());
                    tdNtMemberRegister.setEqu_type(member.getEqu_type());
                    /**
                     * 判断邀请码是否为空，如果邀请码不为空但是没有邀请人，报无效的邀请码
                     */
                    if (tdNtMemberRegister.getInvite_code() != null) {
                        TdNtMemberInvite tdNtMember = tdNtMemberDao.findTdNtMemberInvite(tdNtMemberRegister.getInvite_code());
                        if (tdNtMember != null) {
                            Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
                            Integer memb_reward_limit = Integer.valueOf(tsNtWebSiteConfIndexMap.get("20").getData_value());// 邀请人数上限：20人，超过上限后无邀请奖励金，为0时表示不限制
                            Integer memb_cover_int_reward = Integer.valueOf(tsNtWebSiteConfIndexMap.get("19").getData_value());// 奖励金额：5元
                            if (memb_reward_limit.equals(0)) {
                                /**
                                 * 用户注册
                                 */
                                tdNtMemberRegister.setMemb_islock("1");
                                tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                                tdNtMemberRegister.setMemb_phone_area("86");
                                tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                                tdNtMemberRegister.setToken(CommonUtil.getToken());
                                tdNtMemberRegister.setMemb_password(MD5.code(tdNtMemberRegister.getMemb_password()));
                                tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                                tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                                        tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                                ));

                                tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                                tdNtMemberRegister.setMemb_sex("1");
                                // 用户余额加上邀请奖励
                                tdNtMemberRegister.setMemb_balance(new BigDecimal(memb_cover_int_reward));
                                tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                                tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);
                                /**
                                 * 插入邀请的记录
                                 */
                                Timestamp date = new Timestamp(System.currentTimeMillis());
                                TdNtMembInvitation tdNtMembInvitation = new TdNtMembInvitation();
                                tdNtMembInvitation.setInt_memb_id(tdNtMember.getMemb_id());
                                tdNtMembInvitation.setCover_int_memb_id(tdNtMemberRegister.getMemb_id());
                                tdNtMembInvitation.setRegister_time(date);
                                tdNtMembInvitation.setRegister_month(CommonUtil.getMonth(now));
//								tdNtMembInvitation.setInt_reward(new BigDecimal("2"));
                                tdNtMembInvitation.setCover_int_reward(new BigDecimal(memb_cover_int_reward));
                                tdNtMemberDao.insertInvit(tdNtMembInvitation);
                                Map<String, Object> map = new HashMap<>();
                                if (version >= 5) {
                                    map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtMemberRegister.getMemb_id()));
                                    map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());

                                }
                                map.put("token", tdNtMemberRegister.getToken());
                                map.put("uid", tdNtMemberRegister.getUid());
                                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                                retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                                retInfo.setObj(map);
                                // 分配助教 1
                                Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
                                allotAssistant(tdNtMemberRegister.getMemb_id(), sms);
                                MemcachedUtils.delete("register" + tdNtMemberRegister.getMemb_phone());

                                /**
                                 * 新用户奖励
                                 * 注册人添加资金变动记录
                                 */
                                TdNtMembFoundChangeInset tdNtMembFoundChangeInsetRegister = new TdNtMembFoundChangeInset();
                                tdNtMembFoundChangeInsetRegister.setMemb_id(tdNtMemberRegister.getMemb_id());
                                tdNtMembFoundChangeInsetRegister.setMfchg_back_amount(new BigDecimal(memb_cover_int_reward));
                                tdNtMembFoundChangeInsetRegister.setMfchg_change_amount(new BigDecimal(memb_cover_int_reward));
                                tdNtMembFoundChangeInsetRegister.setMfchg_change_month(CommonUtil.getMonth(now));
                                tdNtMembFoundChangeInsetRegister.setMfchg_change_name("注册奖励");
                                tdNtMembFoundChangeInsetRegister.setMfchg_change_type("1");
                                tdNtMembFoundChangeInsetRegister.setMfchg_front_amount(new BigDecimal(0));
                                tdNtMembFoundChangeInsetRegister.setState("2");
                                tdNtMembFoundChangeInsetRegister.setMfchg_number(CommonUtil.getOrderNub());
                                tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInsetRegister);

                                tdNtMemberDao.updateTdNtMemberBalance(tdNtMember);
                            } else {
                                /**
                                 * 判断用户邀请码邀请的人数
                                 */
                                int size = tdNtMemberDao.findInviteSize(tdNtMember.getMemb_id());
                                if (size < memb_reward_limit) {
                                    /**
                                     * 用户注册
                                     */
                                    tdNtMemberRegister.setMemb_islock("1");
                                    tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                                    tdNtMemberRegister.setMemb_phone_area("86");
                                    tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                                    tdNtMemberRegister.setToken(CommonUtil.getToken());
                                    tdNtMemberRegister.setMemb_password(MD5.code(tdNtMemberRegister.getMemb_password()));
                                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                                    tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                                            tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                                    ));

                                    tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                                    tdNtMemberRegister.setMemb_sex("1");
                                    /**
                                     * 用户余额加上邀请奖励
                                     */
                                    tdNtMemberRegister.setMemb_balance(new BigDecimal(memb_cover_int_reward));
                                    tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                                    tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);
                                    /**
                                     * 插入邀请的记录
                                     */
                                    Timestamp date = new Timestamp(System.currentTimeMillis());
                                    TdNtMembInvitation tdNtMembInvitation = new TdNtMembInvitation();
                                    tdNtMembInvitation.setInt_memb_id(tdNtMember.getMemb_id());
                                    tdNtMembInvitation.setCover_int_memb_id(tdNtMemberRegister.getMemb_id());
                                    tdNtMembInvitation.setRegister_time(date);
                                    tdNtMembInvitation.setRegister_month(CommonUtil.getMonth(now));
//								tdNtMembInvitation.setInt_reward(new BigDecimal("2"));
                                    tdNtMembInvitation.setCover_int_reward(new BigDecimal(memb_cover_int_reward));
                                    tdNtMemberDao.insertInvit(tdNtMembInvitation);
                                    Map<String, Object> map = new HashMap<>();
                                    if (version >= 5) {
                                        map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtMemberRegister.getMemb_id()));
                                        map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());

                                    }
                                    map.put("token", tdNtMemberRegister.getToken());
                                    map.put("uid", tdNtMemberRegister.getUid());
                                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                                    retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                                    retInfo.setObj(map);
                                    // 分配助教 2
                                    Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
                                    allotAssistant(tdNtMemberRegister.getMemb_id(), sms);

                                    MemcachedUtils.delete("register" + tdNtMemberRegister.getMemb_phone());

                                    /**
                                     * 注册人添加资金变动记录
                                     */
                                    TdNtMembFoundChangeInset tdNtMembFoundChangeInsetRegister = new TdNtMembFoundChangeInset();
                                    tdNtMembFoundChangeInsetRegister.setMemb_id(tdNtMemberRegister.getMemb_id());
                                    tdNtMembFoundChangeInsetRegister.setMfchg_back_amount(new BigDecimal(memb_cover_int_reward));
                                    tdNtMembFoundChangeInsetRegister.setMfchg_change_amount(new BigDecimal(memb_cover_int_reward));
                                    tdNtMembFoundChangeInsetRegister.setMfchg_change_month(CommonUtil.getMonth(now));
                                    tdNtMembFoundChangeInsetRegister.setMfchg_change_name("注册奖励");
                                    tdNtMembFoundChangeInsetRegister.setMfchg_change_type("1");
                                    tdNtMembFoundChangeInsetRegister.setMfchg_front_amount(new BigDecimal("0"));
                                    tdNtMembFoundChangeInsetRegister.setState("2");
                                    tdNtMembFoundChangeInsetRegister.setMfchg_number(CommonUtil.getOrderNub());
                                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInsetRegister);

                                    TdNtMemberDetail tdNtMemberDetail = tdNtMemberDao.findTdNtMemberDetail(tdNtMember.getMemb_id());
                                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMember);
                                } else {
                                    // 邀请人数超过上限，不给邀请奖励金
                                    tdNtMemberRegister.setMemb_balance(new BigDecimal("0"));
                                    /**
                                     * 用户注册
                                     */
                                    tdNtMemberRegister.setMemb_islock("1");
                                    tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                                    tdNtMemberRegister.setMemb_phone_area("86");
                                    tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                                    tdNtMemberRegister.setToken(CommonUtil.getToken());
                                    tdNtMemberRegister.setMemb_password(MD5.code(tdNtMemberRegister.getMemb_password()));
                                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                                    tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                                            tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                                    ));
                                    tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                                    tdNtMemberRegister.setMemb_sex("1");
                                    tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                                    tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);

                                    Map<String, Object> map = new HashMap<>();
                                    if (version >= 5) {
                                        map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtMemberRegister.getMemb_id()));
                                        map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());

                                    }
                                    map.put("token", tdNtMemberRegister.getToken());
                                    map.put("uid", tdNtMemberRegister.getUid());
                                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                                    retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                                    retInfo.setObj(map);
                                    // 分配助教 3
                                    Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
                                    allotAssistant(tdNtMemberRegister.getMemb_id(), sms);
                                    MemcachedUtils.delete("register" + tdNtMemberRegister.getMemb_phone());
                                }
                            }
                        } else {
                            /**
                             * 邀请码不存在直接返回
                             */
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("INVITECODE.ERROR"));
                            return retInfo;
                        }
                    } else {
                        tdNtMemberRegister.setMemb_balance(new BigDecimal("0"));
                        /**
                         * 用户注册
                         */
                        tdNtMemberRegister.setMemb_islock("1");
                        tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                        tdNtMemberRegister.setMemb_phone_area("86");
                        tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                        tdNtMemberRegister.setToken(CommonUtil.getToken());
                        tdNtMemberRegister.setMemb_password(MD5.code(tdNtMemberRegister.getMemb_password()));
                        tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                        tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                                tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                        ));
                        tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                        tdNtMemberRegister.setMemb_sex("1");
                        tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                        tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);

                        Map<String, Object> map = new HashMap<>();
                        if (version >= 5) {
                            map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtMemberRegister.getMemb_id()));
                            map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());

                        }
                        map.put("token", tdNtMemberRegister.getToken());
                        map.put("uid", tdNtMemberRegister.getUid());
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                        retInfo.setObj(map);
                        // 分配助教 4
                        Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
                        allotAssistant(tdNtMemberRegister.getMemb_id(), sms);
                        MemcachedUtils.delete("register" + tdNtMemberRegister.getMemb_phone());
                    }

                }
                TdNtMember tdNtMember = tdNtMemberDao.findTdNtMemberByPhone(member.getMemb_phone());
                MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    // 分配助教
    public synchronized void allotAssistant(Integer memb_id, Sms sms){
        logger.info("分配助教 ----------");
        // 查询接单数最少的助教
        Assistant assistant = tdNtMemberDao.findAssistantForMinMembSize();
        logger.info("分配助教 【1】查询接单数最少的助教----------");
        // 设置助教
        tdNtMemberDao.assistantToMemb(memb_id,assistant.getId(),assistant.getName());
        logger.info("分配助教 【2】设置助教----------");
        // 助教人数加1
        tdNtMemberDao.updateAssistantStudentSizePlus(assistant.getId());
        logger.info("分配助教 【3】助教人数加1----------");

        // 发送短信，告诉学生助教老师的联系方式
        if (StringUtils.isNotBlank(sms.getMemb_phone())) {
            // 【外教君】您已成功注册外教君，如需咨询请添加您专属助教老师 Robin，微信（手机同号）：13900001234
            String content = "您已成功注册外教君账号，如需咨询请添加您专属助教老师" + assistant.getName() + "，微信（手机同号）：" + assistant.getWeixin();
            SMSUtil.sendSms(sms, content);
        }

    }

    @Override
    public RetInfo loginByCode(MemberLoginByCode member, int version) {
        String logInfo = this.getClass().getName() + ":loginByCode:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        Date now = new Date();
        try {
            Object o_vcode = MemcachedUtils.get("registerAndLogin" + member.getMemb_phone());//读取缓存中的验证码
            String userCode = member.getCode();
            if (o_vcode == null || !userCode.trim().equals(o_vcode.toString())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.CODE.ERROR"));
            } else {
                TdNtMemberRegisterSms memberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(member.getMemb_phone());
                /**
                 * 判断用户不存在
                 */
                if (memberRegisterSms == null) {
                    /**
                     * 用户注册
                     */
                    TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
                    tdNtMemberRegister.setMemb_phone(member.getMemb_phone());
                    tdNtMemberRegister.setInvite_code(member.getInvite_code());
                    tdNtMemberRegister.setMemb_phone_area(member.getMemb_phone_area());
                    tdNtMemberRegister.setEqu_client_id(member.getEqu_client_id());
                    tdNtMemberRegister.setEqu_type(member.getEqu_type());
                    tdNtMemberRegister.setMemb_islock("1");
                    tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                    tdNtMemberRegister.setMemb_phone_area("86");
                    tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                    tdNtMemberRegister.setMemb_balance(new BigDecimal(0));
                    tdNtMemberRegister.setToken(CommonUtil.getToken());
                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                    tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                            tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                    ));
                    tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                    tdNtMemberRegister.setMemb_sex("1");
                    tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                    tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);

                    // 分配助教
                    Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
                    allotAssistant(tdNtMemberRegister.getMemb_id(), sms);
                }
                TdNtMember tdNtMember = tdNtMemberDao.findTdNtMemberByPhone(member.getMemb_phone());
                String appKey = rongCloudConfig.getAppkey();
                String appSecret = rongCloudConfig.getSecret();
                TokenResult tokenResult = null;

                if (tdNtMember.getMemb_islock().equals("1")) {
                    /**
                     * 更新用户token
                     */
                    TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
                    tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMemberToken.setToken(CommonUtil.getToken());
                    tdNtMemberToken.setEqu_client_id(member.getEqu_client_id());
                    tdNtMemberToken.setEqu_type(member.getEqu_type());
                    tdNtMemberToken.setThird_token(null);
                    tdNtMemberToken.setNowLoginType(Constants.ThirdPartyType.mobile_Type);
                    tdNtMemberDao.updateTdNtMemberInfo(tdNtMemberToken);
                    /**
                     * 删除把用户对象放入memcached原有用户对象
                     */
                    MemcachedUtils.delete(tdNtMember.getToken());
                    /**
                     * 把用户对象放入memcached
                     */
                    tdNtMember.setToken(tdNtMemberToken.getToken());
                    tdNtMember.setEqu_client_id(tdNtMemberToken.getEqu_client_id());
                    tdNtMember.setEqu_type(tdNtMemberToken.getEqu_type());
                    MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);

                    Map<String, Object> map = new HashMap<>();
                    if (tdNtMember.getRongcloud_token() == null || tdNtMember.getRongcloud_token() == "") {
                        // 获取融云 Token 方法
                        Reader reader = null;
                        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
                        String memb_id = "student" + tdNtMember.getMemb_id();
                        String memb_head_portraituri = tdNtMember.getMemb_head_portrait();
                        if (!memb_head_portraituri.contains("http")) {
                            memb_head_portraituri = WAIJIAOJUN_URL + memb_head_portraituri;
                        }
                        tokenResult = rongCloud.user.getToken(memb_id, tdNtMember.getMemb_name(), memb_head_portraituri);
                        tdNtMemberDao.updateRongCloudToken(tokenResult.token, Integer.valueOf(tdNtMember.getMemb_id()));
                        if (tokenResult.getToken() != null && tokenResult.getToken() != "") {
                            map.put("rongCloudToken", tokenResult.getToken());
                        }
                        logger.info(tokenResult.toString());
                    } else {
                        map.put("rongCloudToken", tdNtMember.getRongcloud_token());
                    }
                    //判断用户有没有领取优惠券，没有的话默认领取
                    int reserve_package = tdNtMemberDao.findUseReservePackage(tdNtMember.getMemb_id());
                    Date date = DateUtil.createDate("2018-06-01 00:00:00");
                    if (reserve_package == 0 && tdNtMember.getMemb_register_time().after(date)) {
                        //用户领取红包
                        // 1. 添加红包领取记录
                        MembNewUserScholarship pojo = new MembNewUserScholarship(tdNtMember.getMemb_id());
                        membNewUserScholarshipDao.insert(pojo);

                        // 2.添加到优惠券表中
                        DiscountCoupon discountCoupon = new DiscountCoupon();
                        discountCoupon.setCourse_type(1);
                        discountCoupon.setMemb_id(tdNtMember.getMemb_id());
                        discountCoupon.setDeleted(0);
                        discountCoupon.setOver((double) 0);
                        discountCoupon.setSubtract((double) 120);
                        discountCoupon.setDiscount_state(0);
                        discountCouponDao.insertDiscountCoupon(discountCoupon);
                    }
                    if (version >= 5) {
                        map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtMember.getMemb_id()));
                        map.put("Identifier", Constants.member + tdNtMember.getMemb_id());

                    }
                    map.put("token", tdNtMember.getToken());
                    map.put("uid", tdNtMember.getUid());
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                    retInfo.setObj(map);
                    MemcachedUtils.delete("register" + tdNtMember.getMemb_phone());
                }
                MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo registerByCode(MemberRegisterByCode member, int version){
        String logInfo = this.getClass().getName() + ":registerByCode:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = RetInfo.getSuccessInfo();
        Map<String,Object> map = new HashMap<>();
        try {
            TdNtMemberRegisterSms memberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(member.getMemb_phone());
            if(memberRegisterSms!=null){
                retInfo.setTip("该手机号码已注册，请更换手机号");
                retInfo.setMark("1");
                return retInfo;
            }
            /**
             * 用户注册
             */
            TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
            tdNtMemberRegister.setMemb_phone(member.getMemb_phone());
            tdNtMemberRegister.setInvite_code(member.getInvite_code());
            tdNtMemberRegister.setMemb_phone_area(member.getMemb_phone_area());
            tdNtMemberRegister.setMemb_islock("1");
            tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
            tdNtMemberRegister.setMemb_phone_area("86");
            tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
            tdNtMemberRegister.setToken(CommonUtil.getToken());
            tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
            tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                    tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
            ));
            tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
            tdNtMemberRegister.setMemb_sex("1");
            tdNtMemberRegister.setUid(UUID.randomUUID().toString());
            int memb_id = tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);


            /**
             * 判断邀请码是否为空，如果邀请码不为空但是没有邀请人，报无效的邀请码
             */
            if (member.getInvite_code() != null) {
                TdNtMemberInvite tdNtMember = tdNtMemberDao.findTdNtMemberInvite(member.getInvite_code());
                TdNtMember tdNtMember1 = tdNtMemberDao.findTdNtMemberByPhone(member.getMemb_phone());
                if (tdNtMember != null) {
                    /**
                     * 插入邀请的记录
                     */
                    TdNtInviteByCode tdNtInviteByCode = new TdNtInviteByCode();
                    Timestamp date = new Timestamp(System.currentTimeMillis());
                    tdNtInviteByCode.setMemb_id(tdNtMember.getMemb_id());
                    tdNtInviteByCode.setInvitee_id(tdNtMember1.getMemb_id());
                    tdNtInviteByCode.setCreate_date(date);
                    tdNtInviteByCode.setUpdate_date(date);
                    tdNtMemberDao.insertInviteByCode(tdNtInviteByCode);
                } else {
                    //邀请码不存在报错
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("INVITECODE.ERROR"));
                    return retInfo;
                }

                //判断用户有没有领取优惠券，没有的话默认领取
                int reserve_package = tdNtMemberDao.findUseReservePackage(tdNtMember1.getMemb_id());
                Date date = DateUtil.createDate("2018-06-01 00:00:00");
                if (reserve_package == 0 && tdNtMember1.getMemb_register_time().after(date)) {
                    //用户领取红包
                    // 1. 添加红包领取记录
                    MembNewUserScholarship pojo = new MembNewUserScholarship(tdNtMember1.getMemb_id());
                    membNewUserScholarshipDao.insert(pojo);

                    // 2.添加到优惠券表中
                    DiscountCoupon discountCoupon = new DiscountCoupon();
                    discountCoupon.setCourse_type(1);
                    discountCoupon.setMemb_id(tdNtMember.getMemb_id());
                    discountCoupon.setDeleted(0);
                    discountCoupon.setOver((double) 0);
                    discountCoupon.setSubtract((double) 120);
                    discountCoupon.setDiscount_state(0);
                    discountCouponDao.insertDiscountCoupon(discountCoupon);
                    map.put("discountCoupon",discountCoupon);
                }
                map.put("memb_phone",member.getMemb_phone());
                retInfo.setObj(map);
            }
    } catch (Exception e) {
        retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
        retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
        logger.error(e.getMessage(), e);
    }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo smsRegister(Sms sms) {
        String logInfo = this.getClass().getName() + ":smsRegister:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMemberRegisterSms tdNtMemberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(sms.getMemb_phone());
            //验证手机号是否注册过
            if (tdNtMemberRegisterSms != null) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("该手机号已经注册,请更换手机号");
                return retInfo;
            }

            Map<String, Integer> map = new HashMap<>();
            String dayKey = "day" + sms.getMemb_phone();//每天20条短信的限制的key day+手机号
            String register = "register" + sms.getMemb_phone();
            String sencod = "sencod" + sms.getMemb_phone();

            //今天是否发送过短信，如果发送过短信就校验是否超过20条
            Object o_day = MemcachedUtils.get(dayKey);
            int day_size = 0;
            //如果今天发送过短信，校验是否超过20条
            if (o_day != null) {
                map = (Map<String, Integer>) MemcachedUtils.get(dayKey);
                day_size = map.get("size");
                logger.info("1天内发送短条数：phone:" + sms.getMemb_phone() + ",size:" + day_size);
                //今天短信是否超过20条
                if (day_size >= 20) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                    logger.info("发送短信超过20条" + sms.getMemb_phone());
                    return retInfo;
                }
            }

            //检查60秒是否发送过短信
            if ("0".equals(MemcachedUtils.get(sencod))) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                logger.info("50秒内发送过短信，过于频繁" + sms.getMemb_phone());
                return retInfo;
            }

            String content = "您的验证码为CODE（5分钟内有效，如非本人操作请忽略）";
            String code = SmsCodeUtil.getSmsCode();

            content = content.replace("CODE", code);
            logger.info(content);

            //在数据库中插入短信发送记录
            TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
            twNtSendHis.setPhoneno(sms.getMemb_phone());
            twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
            twNtSendHis.setSms_provider_id(Integer.parseInt(code));

            //调用短信接口发送短信
            boolean flag = SMSUtil.sendSms(sms, content);

            //发送成
            if (flag) {
                //将验证码放入缓存，登录的时候与用户输出的做比较
                if (MemcachedUtils.get(register) == null) {
                    MemcachedUtils.add(register, code, 5 * 60);
                } else {
                    MemcachedUtils.replace(register, code, 5 * 60);
                }

                twNtSendHis.setSms_type("Y");
                twNtSendHisDao.insertTwNtSendHis(twNtSendHis);

                //短信发送成功，记录秒标记
                MemcachedUtils.add(sencod, "0", 50);
                //短信发送成功，日发送次数+1
                map.put("size", day_size + 1);
                MemcachedUtils.add(dayKey, map, 24 * 60 * 60);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));


                return retInfo;
            }
            //发送失败
            else {
                twNtSendHis.setSms_type("N");
                twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                return retInfo;
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
            return retInfo;
        }
    }

    @Override
    public RetInfo registerCoopersion(TdNtMemberRegister member) {
        String logInfo = this.getClass().getName() + ":register:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            if (MemcachedUtils.get("register" + member.getMemb_phone()) == null || !MemcachedUtils.get("register" + member.getMemb_phone()).equals(member.getCode())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.CODE.ERROR"));
            } else {
                TdNtMemberRegisterSms memberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(member.getMemb_phone());
                /**
                 * 判断用户是否已存在
                 */
                if (memberRegisterSms != null) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MEMBER.REGISTER.ERROR"));
                } else {
                    TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
                    tdNtMemberRegister.setMemb_phone(member.getMemb_phone());
                    tdNtMemberRegister.setMemb_password(member.getMemb_password());
                    tdNtMemberRegister.setInvite_code(member.getInvite_code());
                    tdNtMemberRegister.setMemb_phone_area(member.getMemb_phone_area());
                    tdNtMemberRegister.setEqu_client_id(member.getEqu_type());
                    tdNtMemberRegister.setEqu_type(member.getEqu_type());
                    /**
                     * 用户注册
                     */
                    tdNtMemberRegister.setMemb_islock("1");
                    tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                    tdNtMemberRegister.setMemb_phone_area("86");
                    tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
                    tdNtMemberRegister.setToken(CommonUtil.getToken());
                    tdNtMemberRegister.setMemb_password(MD5.code(tdNtMemberRegister.getMemb_password()));
                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                    tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                            tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
                    ));
                    tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                    tdNtMemberRegister.setMemb_sex("1");
                    Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
                    Integer memb_cover_int_reward = Integer.valueOf(tsNtWebSiteConfIndexMap.get("26").getData_value());

                    /**
                     * 用户余额加上邀请奖励
                     */
                    tdNtMemberRegister.setMemb_balance(new BigDecimal(memb_cover_int_reward));
                    tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);
                    /**
                     * 注册人添加资金变动记录
                     */
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInsetRegister = new TdNtMembFoundChangeInset();
                    tdNtMembFoundChangeInsetRegister.setMemb_id(tdNtMemberRegister.getMemb_id());
                    tdNtMembFoundChangeInsetRegister.setMfchg_back_amount(new BigDecimal(memb_cover_int_reward));
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_amount(new BigDecimal(memb_cover_int_reward));
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_month(CommonUtil.getMonth(now));
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_name("注册奖励");
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_type("1");
                    tdNtMembFoundChangeInsetRegister.setMfchg_front_amount(new BigDecimal(0));
                    tdNtMembFoundChangeInsetRegister.setState("2");
                    tdNtMembFoundChangeInsetRegister.setMfchg_number(CommonUtil.getOrderNub());
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInsetRegister);

                    /**
                     * 判断邀请码是否为空
                     */
                    if (tdNtMemberRegister.getInvite_code() != null) {
                        /**
                         * 查找企业码是否存在
                         */
                        TdNtCooperation tdNtCooperation = tdNtCooperationDao.findCooperationCode(tdNtMemberRegister.getInvite_code());
                        if (tdNtCooperation != null) {
                            TdNtCooperationMember tdNtCooperationMember = new TdNtCooperationMember();
                            tdNtCooperationMember.setCpt_id(tdNtCooperation.getCpt_id());
                            tdNtCooperationMember.setMemb_id(tdNtMemberRegister.getMemb_id());
                            //判断合作商用户关联表信息是否存在
                            TdNtCooperationMember findtdNtCooperationMember = tdNtCooperationDao.findTdNtCooperationMember(tdNtCooperationMember);
                            if (findtdNtCooperationMember == null) {
                                tdNtCooperationDao.updateTdNtCooperationMember(tdNtCooperationMember);
                            }
                            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                            retInfo.setTip("企业码!");
                        }
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("token", tdNtMemberRegister.getToken());
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                    retInfo.setObj(map);

                    MemcachedUtils.delete("register" + tdNtMemberRegister.getMemb_phone());

                }
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo thirdregister(TdNtMemberThirdRegister tdNtMemberThirdRegister) {
        String logInfo = this.getClass().getName() + ":thirdregister:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            TdNtMember memberRegisterSms = tdNtMemberDao.findTdNtMemberByLoginTypeAndThirdToken(tdNtMemberThirdRegister.getThird_token(),
                    tdNtMemberThirdRegister.getNowLoginType());
            /**
             * 判断用户是否已存在
             */
            if (memberRegisterSms != null) {
                if (memberRegisterSms.getMemb_islock().equals("1")) {
                    /**
                     * 更新用户token
                     */
                    TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
                    tdNtMemberToken.setMemb_id(memberRegisterSms.getMemb_id());
                    tdNtMemberToken.setToken(CommonUtil.getToken());
                    tdNtMemberToken.setEqu_client_id(memberRegisterSms.getEqu_client_id());
                    tdNtMemberToken.setEqu_type(memberRegisterSms.getEqu_type());
                    tdNtMemberDao.updateTdNtMemberToken(tdNtMemberToken);
                    /**
                     * 删除把用户对象放入memcached原有用户对象
                     */
                    MemcachedUtils.delete(memberRegisterSms.getToken());
                    /**
                     * 把用户对象放入memcached
                     */
                    memberRegisterSms.setToken(tdNtMemberToken.getToken());
                    memberRegisterSms.setEqu_client_id(tdNtMemberToken.getEqu_client_id());
                    memberRegisterSms.setEqu_type(tdNtMemberToken.getEqu_type());
                    MemcachedUtils.add(memberRegisterSms.getToken(), memberRegisterSms, 20 * 24 * 60 * 60);


                    Map<String, Object> map = new HashMap<>();
                    map.put("token", tdNtMemberToken.getToken());
                    map.put("sig", tls_sigature.getUsersig(Constants.member + memberRegisterSms.getMemb_id()));
                    map.put("Identifier", Constants.member + memberRegisterSms.getMemb_id());
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.SUCCESS"));
                    retInfo.setObj(map);

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.ERROR"));
                }
            } else {
                TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
                tdNtMemberRegister.setEqu_client_id(tdNtMemberThirdRegister.getEqu_client_id());
                tdNtMemberRegister.setEqu_type(tdNtMemberThirdRegister.getEqu_type());
                tdNtMemberRegister.setMemb_balance(new BigDecimal("0"));
                /**
                 * 用户注册
                 */
                tdNtMemberRegister.setMemb_islock("1");
                tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(new Date()));
                tdNtMemberRegister.setToken(CommonUtil.getToken());
                if (tdNtMemberThirdRegister.getMemb_head_portrait() != null) {
                    tdNtMemberRegister.setMemb_head_portrait(tdNtMemberThirdRegister.getMemb_head_portrait());
                } else {
                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                }
                if (tdNtMemberThirdRegister.getMemb_name() != null) {
                    tdNtMemberRegister.setMemb_name(tdNtMemberThirdRegister.getMemb_name());
                } else {
                    tdNtMemberRegister.setMemb_name("nativetalk");
                }
                if (tdNtMemberThirdRegister.getMemb_sex() != null) {
                    tdNtMemberRegister.setMemb_sex(tdNtMemberThirdRegister.getMemb_sex());
                } else {
                    tdNtMemberRegister.setMemb_sex("1");
                }
                tdNtMemberRegister.setThird_token(tdNtMemberThirdRegister.getThird_token());
                tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);
                Map<String, Object> map = new HashMap<>();
                map.put("token", tdNtMemberRegister.getToken());
                map.put("sig", tls_sigature.getUsersig(Constants.member + tdNtMemberRegister.getMemb_id()));
                map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                retInfo.setObj(map);
                TdNtMember tdNtMember = tdNtMemberDao.findTdNtMemberByLoginTypeAndThirdToken(tdNtMemberThirdRegister.getThird_token(),
                        tdNtMemberThirdRegister.getNowLoginType());
                MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
